﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Runtime.InteropServices;
using System.Net.Configuration;
using System.Threading;
using System.Diagnostics;
using System.Text.RegularExpressions;
//using System.Globalization;
using System.Net;



/// <summary>
///Public 的摘要说明
/// </summary>
public class Public
{
    [DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest,Int32 host,ref Int64 mac,ref Int32 length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);

	public Public()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}



    public static string GetClientIP()
    {
        string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (null == result || result == String.Empty)
        {
            result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }

        if (null == result || result == String.Empty)
        {
            result = HttpContext.Current.Request.UserHostAddress;
        }
        return result;
    }


    public static  string GetCustomerMac(string IP)
    {
        string dirResults = "";
        ProcessStartInfo psi = new ProcessStartInfo();
        Process proc = new Process();
        psi.FileName = "nbtstat";
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = true;
        psi.Arguments = "-a " + IP;
        psi.UseShellExecute = false;
        psi.CreateNoWindow = true;
        proc = Process.Start(psi);
        dirResults = proc.StandardOutput.ReadToEnd();
        proc.WaitForExit();

        //匹配mac地址
        Match m = Regex.Match(dirResults, "\\w+\\-\\w+\\-\\w+\\-\\w+\\-\\w+\\-\\w\\w");

        //若匹配成功则返回mac，否则返回找不到主机信息
        if (m.ToString() != "")
        {
            return m.ToString();
        }
        else
        {
            return "找不到主机信息";
        }

    }





    public static string GetClientMAC()
{
   // 在此处放置用户代码以初始化页面
   //try
   //{
       string userip = HttpContext.Current.Request.UserHostAddress;
       string strClientIP = HttpContext.Current.Request.UserHostAddress.ToString().Trim();
    Int32 ldest = inet_addr(strClientIP); //目的地的ip
    Int32 lhost = inet_addr("");   //本地服务器的ip
    Int64 macinfo = new Int64();
    Int32 len = 6;
    int res = SendARP(ldest,0, ref macinfo, ref len);
    string mac_src=macinfo.ToString("X");
    //if(mac_src == "0")
    //{
    // if(userip=="127.0.0.1")
    //  Response.Write ("正在访问Localhost!");
    // else
    //  Response.Write ("欢迎来自IP为" + userip + "的朋友！" + "<br>");
    // return;
    //}

    while(mac_src.Length<12)
    {
     mac_src = mac_src.Insert(0,"0");
    }

    string mac_dest="";

    for(int i=0;i<11;i++)
    {
     if (0 == (i % 2))
     {
      if ( i == 10 )
      {
       mac_dest = mac_dest.Insert(0,mac_src.Substring(i,2));
      }
      else
      {
       mac_dest ="-" + mac_dest.Insert(0,mac_src.Substring(i,2));
      }
     }
    }
    //Response.Write ("欢迎来自IP为"+userip+ "<br>" + ",MAC地址为"+mac_dest+"的朋友！"

    // +   "<br>");
       return mac_dest;
   }
   //catch(Exception err)
   //{
   // //Response.Write(err.Message);
   //}
//}

    /// <summary>
    ///根据输入的身份证ID，输出该ID号相应的地区信息
    /// </summary>
    public static string GetID_Detail_Adress(string ID)
    {
        string adress="";
        DataSet_fp_DyhTableAdapters.Dyh_ID_codeTableAdapter id_code = new DataSet_fp_DyhTableAdapters.Dyh_ID_codeTableAdapter();

        ID = ID.Trim().Substring(0, 6);

        if (ID.Substring(4, 2) != "00" ) 
        {
            if (id_code.Get_Data_By_Full_Code(ID).Rows.Count > 0)
            {
                adress = id_code.Get_Data_By_Full_Code(ID).Rows[0]["name"].ToString().Trim();
            }
            else 
            {
                return "无此身份证地址信息！";
            }
        }

        if (ID.Substring(2, 4) != "0000")
        {
            if (id_code.Get_Data_By_Full_Code(ID.Substring(0, 4) + "00").Rows.Count > 0)
            {
                adress =  id_code.Get_Data_By_Full_Code(ID.Substring(0, 4) + "00").Rows[0]["name"].ToString().Trim() +adress ;
            }
            else
            {
                return "无此身份证地址信息！";
            }
        }
        if (id_code.Get_Data_By_Full_Code(ID.Substring(0, 2) + "0000").Rows.Count > 0)
        {
            adress = id_code.Get_Data_By_Full_Code(ID.Substring(0, 2) + "0000").Rows[0]["name"].ToString().Trim() + adress;
        }
        else
        {
            return "无此身份证地址信息！";
        }

            if (adress == "")
            {
                return "无此身份证地址信息！";
            }
            else
            {
                return adress;
            }

    }

    /// <summary>
    ///根据输入的身份证ID的前17位，输出该ID号相应的校验位
    /// </summary>
    public static string GetID_CRC_Data(string ID)
    {
        int sum=0;
        string CRC="";
        for (int i = 0; i <= 16; i++)
        {
            sum = sum + Convert.ToInt32(ID.Substring(i, 1)) * Convert.ToInt32((Math.Pow(2, (17 - i)) % 11));
        }
        sum = sum % 11;

        if (sum > 2)
        {
            sum= 12 - sum;
            CRC = sum.ToString();
        }
        else if (sum == 0)
        {
            CRC = "1";
        }
        else if (sum == 1)
        {
            CRC = "2";
        }
        else if (sum == 2)
        {
            CRC = "X";
        }
        return CRC;
    }

    /// <summary>
    ///根据输入的18位身份证ID，判断校验位是否有效;
    /// </summary>
    public static bool ID_CRC_IsValid(string ID)
    {
        int sum = 0;
        string CRC = "";
        for (int i = 0; i <= 16; i++)
        {
            sum = sum + Convert.ToInt32(ID.Substring(i, 1)) * Convert.ToInt32((Math.Pow(2, (17 - i)) % 11));
        }
        sum = sum % 11;

        if (sum > 2)
        {
            sum = 12 - sum;
            CRC = sum.ToString();
        }
        else if (sum == 0)
        {
            CRC = "1";
        }
        else if (sum == 1)
        {
            CRC = "2";
        }
        else if (sum == 2)
        {
            CRC = "X";
        }

        if (CRC == ID.Substring(17, 1))
        {
            return true;
        }
        else 
        {
            return false;
        }
    }

    /// <summary>
    ///根据输入的8位日期格式（yyyyMMdd），判断日期是否有效;
    /// </summary>
    public static bool Date_Check(string time)
    {
        //IFormatProvider ifp = new CultureInfo("fr-FR", true);
        try
        {
            DateTime.ParseExact(time, "yyyyMMdd", null);
        }
        catch (Exception)
        {
            return false;
        }
        return true;

        //IFormatProvider ifp = new CultureInfo("fr-FR", true);
        //try
        //{
        //    DateTime.Parse(time, ifp, DateTimeStyles.AllowLeadingWhite);
        //}
        //catch (Exception)
        //{
        //    return false;
        //}
        //return true;   
    }


    /// <summary>
    ///根据输入的网址，获取其IP地址列表集合;
    /// </summary>
    public static IPAddress[] URL_to_All_IP(string URL)
    {   
        if (URL.IndexOf("//", 0)>0)
        {
            URL = URL.Substring(URL.IndexOf("//", 0) + 2);
        }

        if (URL.IndexOf("/", 0)>0)
        {
            URL = URL.Substring(0, URL.IndexOf("/", 0));
        }
        try
        {
            IPHostEntry IPHost = Dns.GetHostEntry(URL);
            string[] aliases = IPHost.Aliases;
            IPAddress[] address = IPHost.AddressList;  //返回的地址列表保存在集合address中
            return address;
        }
        catch (Exception)
        {
            IPAddress[] address;
            address = null; //如果返回出错，就返回Null值 
            return address;
        }
    }


    /// <summary>
    ///根据输入的网址，获取其首个IP地址;
    /// </summary>
    public static string URL_to_Single_IP(string URL)
    {
        string ip;
        try
        {
            IPHostEntry IPHost = Dns.GetHostEntry(URL);
            string[] aliases = IPHost.Aliases;
            IPAddress[] address = IPHost.AddressList;
            ip = address[0].ToString();
            return ip;
        }
        catch (Exception)
        {
            return "不存在这样的主机";
        }

    }
}
